﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CrawlerCore;
using HtmlAgilityPack;
using WCrawlerLib;
using System.Threading;
using System.Threading.Tasks;
using System.Configuration;
using PhotobucketNet;
using System.Text.RegularExpressions;

namespace WCrawler.Controls
{
    public partial class ucSearchIMDB : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        public void SearchIMDB_DataBind()
        {
            Reset();
            if (Session["PostId"] != null)
            {
                int postId = (int)Session["PostId"];
                Post objPost = new Post();
                objPost = objPost.GetPost(postId);
                txtSearch.Text = objPost.PostTitle;
            }
        }

        public void Reset()
        {
            txtFilmUrl.Text = "";

            txtPrimaryImage.Text = "";
            txtSubTitle.Text = "";
            txtRuntime.Text = "";
            txtGenres.Text = "";
            txtReleaseDate.Text = "";
            txtDescription.Text = "";
            txtRating.Text = "";
            txtDirectors.Text = "";
            txtActors.Text = "";
            txtLanguage.Text = "";
            txtStoryLine.Text = "";
            txtScreenShot.Text = "";
        }

        public void GetFilmInformation(string filmUrl, HtmlDocument doc)
        {
            BrowserSession_General br = new BrowserSession_General();
            //Film Url
            txtFilmUrl.Text = filmUrl;
            //Title
            HtmlNodeCollection nodeCollection = doc.DocumentNode.SelectNodes(@".//td[@id='overview-top']/h1/text()");
            if (nodeCollection != null)
            {
                txtSubTitle.Text = nodeCollection[0].InnerHtml.Trim();
            }
            //year
            //txtHeadTitle.Text += " (" + doc.DocumentNode.SelectNodes(@".//td[@id='overview-top']/h1//a/text()")[0].InnerHtml + ")";
            nodeCollection = doc.DocumentNode.SelectNodes(@".//td[@id='overview-top']/h1//a/text()");
            string year = "";
            if (nodeCollection != null)
            {
                year = nodeCollection[0].InnerHtml.Trim();
            }
            else
            {
                nodeCollection = doc.DocumentNode.SelectNodes(@".//td[@id='overview-top']/h1/span/text()");
                if (nodeCollection != null)
                {
                    Regex r = new Regex("(?<num>[0-9]+)");
                    Match m = r.Match(nodeCollection[0].InnerHtml.Trim());
                    if (m.Success)
                        year = m.Result("${num}");
                }
            }

            if (year != string.Empty)
            {
                year = "(" + year + ")";
                if (!txtSubTitle.Text.Contains(year))
                    txtSubTitle.Text += " " + year;
            }

            //txtHeadTitle.Text += " (" + doc.DocumentNode.SelectNodes(@".//td[@id='overview-top']/h1//a/text()")[0].InnerHtml + ")";
            //txtSubTitle.Text = txtHeadTitle.Text;
            //txtSubTitle.Text = searchTitle;

            //Primary Image 
            nodeCollection = doc.DocumentNode.SelectNodes(@".//table[@id='title-overview-widget-layout']//td[@id='img_primary']/a");
            if (nodeCollection != null)
            {
                string urlImagePrimary = nodeCollection[0].Attributes["href"].Value;
                HtmlDocument docImagePrimary = br.Get("http://www.imdb.com" + urlImagePrimary);
                txtPrimaryImage.Text = docImagePrimary.DocumentNode.SelectNodes(@".//img[@id='primary-img']")[0].Attributes["src"].Value;
            }

            //Description
            nodeCollection = doc.DocumentNode.SelectNodes(@".//p[@itemprop='description']/text()");
            if (nodeCollection != null)
            {
                txtDescription.Text = nodeCollection[0].InnerHtml.Trim();
            }

            //Runtime
            nodeCollection = doc.DocumentNode.SelectNodes(@".//div[@class='infobar']/text()");
            if (nodeCollection != null)
            {
                txtRuntime.Text = nodeCollection[1].InnerHtml.Replace("-", "").Trim();
            }

            //4. Rating .//span[@itemprop='ratingValue']
            nodeCollection = doc.DocumentNode.SelectNodes(@".//span[@itemprop='ratingValue']/text()");
            if (nodeCollection != null)
            {
                txtRating.Text = nodeCollection[0].InnerHtml.Trim();
            }
            //txtRating.Text = doc.DocumentNode.SelectNodes(@".//span[@itemprop='ratingValue']/text()")[0].InnerHtml;

            //5. Release Date
            nodeCollection = doc.DocumentNode.SelectNodes(@".//time[@itemprop='datePublished']/text()");
            if (nodeCollection != null)
            {
                txtReleaseDate.Text = nodeCollection[0].InnerHtml.Trim();
            }
            //txtReleaseDate.Text = doc.DocumentNode.SelectNodes(@".//time[@itemprop='datePublished']/text()")[0].InnerHtml;

            //6. Directors
            HtmlNodeCollection directorCollection = doc.DocumentNode.SelectNodes(@".//a[@itemprop='director']/text()");
            string directors = "";
            foreach (HtmlNode node in directorCollection)
            {
                directors += node.InnerHtml.Trim() + ", ";
            }
            txtDirectors.Text = directors.Substring(0, directors.Length - 2);

            //7. Actors
            HtmlNodeCollection actorsCollection = doc.DocumentNode.SelectNodes(@".//a[@itemprop='actors']/text()");
            string actors = "";
            foreach (HtmlNode node in actorsCollection)
            {
                actors += node.InnerHtml + ", ";
            }
            txtActors.Text = actors.Substring(0, actors.Length - 2);

            //get Genre
            HtmlNodeCollection genresCollection = doc.DocumentNode.SelectNodes(@".//a[@itemprop='genre']/text()");
            string genres = "";
            foreach (HtmlNode node in genresCollection)
            {
                genres += node.InnerHtml + " | ";
            }
            txtGenres.Text = genres.Substring(0, genres.Length - 3);

            //get Language
            nodeCollection = doc.DocumentNode.SelectNodes(@".//a[@itemprop='inLanguage']/text()");
            if (nodeCollection != null)
            {
                txtLanguage.Text = nodeCollection[0].InnerHtml.Trim();
            }
            //txtLanguage.Text = doc.DocumentNode.SelectNodes(@".//a[@itemprop='inLanguage']/text()")[0].InnerHtml;

            //get Storyline
            nodeCollection = doc.DocumentNode.SelectNodes(@".//div[@id='maindetails_center_bottom']/div[@class='article' and ./h2/text() = 'Storyline']/p/text()");
            if (nodeCollection != null)
            {
                txtStoryLine.Text = nodeCollection[0].InnerHtml.Trim();
            }
            //txtStoryLine.Text = doc.DocumentNode.SelectNodes(@".//div[@id='maindetails_center_bottom']/div[@class='article' and ./h2/text() = 'Storyline']/p/text()")[0].InnerHtml.Trim();

            //ScreenShots .//div[@class='mediastrip']/a/@href
            string urlScreenShotPrimary = "";
            object objLock = new object();
            HtmlNodeCollection screenShotCollection = doc.DocumentNode.SelectNodes(@".//div[@class='mediastrip']/a");
            Parallel.ForEach<HtmlNode>(screenShotCollection, node =>
            {
                HtmlDocument docScreenShotPrimary = br.Get("http://www.imdb.com" + node.Attributes["href"].Value);
                if (docScreenShotPrimary != null)
                {
                    lock (objLock)
                    {
                        urlScreenShotPrimary += docScreenShotPrimary.DocumentNode.SelectNodes(@".//img[@id='primary-img']")[0].Attributes["src"].Value + "\n";
                    };
                }

            });
            txtScreenShot.Text = urlScreenShotPrimary;
        }

        protected void btnSearchLoad_Click(object sender, EventArgs e)
        {
            Reset();
            BrowserSession_General br = new BrowserSession_General();
            //==============================================================
            //Get template search: "[Film Name] ([Year])"
            string filmName = txtSearch.Text;
            Regex r = new Regex(@"^.+ (\(|)\d+(\)|)");
            Match m = r.Match(filmName);
            if (m.Success)
            {
                filmName = m.Value;
            }

            //==============================================================
            //Search film
            string[] words = filmName.Split(new char[] { ' ' });
            List<string> wordList = new List<string>();
            foreach (string word in words)
            {
                wordList.Add(HttpUtility.UrlEncode(word));
            }

            string query = string.Join("+", wordList.ToArray());
            string url = "http://www.imdb.com/find?s=tt&q=" + query;
            try
            {
                HtmlDocument doc = br.Get(url);
                string filmUrl = br.Response.ResponseUri.AbsoluteUri;
                if (br.Response.ResponseUri.AbsoluteUri == url)
                {
                    string xpath = ".//a[contains(@onclick,'find-media-title')]";
                    HtmlNodeCollection nodeCollection = doc.DocumentNode.SelectNodes(xpath);
                    foreach (HtmlNode node in nodeCollection)
                        filmUrl = "http://www.imdb.com" + node.Attributes["href"].Value;
                    //After get title url then get film information
                    doc = br.Get(filmUrl);
                    GetFilmInformation(filmUrl, doc);
                }
                else
                {
                    GetFilmInformation(filmUrl, doc);
                }
                //Auto create post
                //btnCreatePost_Click(null, null);
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }

        protected void btnCreatePost_Click(object sender, EventArgs e)
        {
            txtSubTitle.Text = txtSearch.Text;
            ////Write full description
            ////Image
            //txtPost.Text = "[IMG]" + txtPrimaryImage.Text + "[/IMG]\n\n";
            //Title
            //txtPost.Text += "[SIZE=\"3\"][COLOR=\"DarkOrange\"]" + txtSubTitle.Text + "[/COLOR][/SIZE]\n\n";
            txtPost.Text = "[POSTER]\n\n";
            txtPost.Text += "[SIZE=\"3\"]" + txtSubTitle.Text + "[/SIZE]\n\n";

            //IMDB Info
            txtPost.Text += "[B][U]IMDB Information:[/U][/B]\n";
            txtPost.Text += "[QUOTE]\n";
            //Add IMDB url
            txtPost.Text += "[CODE]\n";
            txtPost.Text += txtFilmUrl.Text + "\n";
            txtPost.Text += "[/CODE]\n";
            //Infobar
            txtPost.Text += "[B]" + txtSubTitle.Text + " - " + txtRuntime.Text + " - " + txtGenres.Text + " - " + txtReleaseDate.Text + "[/B]\n\n";
            //Rating
            if (txtRating.Text != string.Empty)
            {
                if (int.Parse(txtRating.Text.Substring(0, 1)) >= 7)
                    txtPost.Text += "[B]Rating:[/B] " + txtRating.Text + "\n";
            }
            //Description
            txtPost.Text += "[B]Description:[/B] " + txtDescription.Text + "\n";
            //Director
            txtPost.Text += "[B]Directors:[/B] " + txtDirectors.Text + "\n";
            //Stars:
            txtPost.Text += "[B]Stars:[/B] " + txtActors.Text + "\n";
            //Story Line
            txtPost.Text += "[B]Story line:[/B] " + txtStoryLine.Text + "\n";
            //Close IMDB Info
            txtPost.Text += "[/QUOTE]\n\n";

            txtPost.Text += "[B][U]Screenshots:[/U][/B]\n";
            txtPost.Text += "[SCREENSHOTS]\n\n";

            txtPost.Text += "[B][U]Download links:[/U][/B]\n";
            txtPost.Text += "[DOWNLOADS]";
            
            //string[] screenshots = txtScreenShot.Text.Trim().Split(new char[] { '\n' });
            //if (screenshots.Count() > 0)
            //{
            //    //ScreenShot
            //    txtPost.Text += "[B][U]Screenshots:[/U][/B]\n\n";
            //    List<string> screenList = new List<string>();
            //    foreach (string screenshot in screenshots)
            //    {
            //        screenList.Add("[IMG]" + screenshot + "[/IMG]\n");
            //    }
            //    txtPost.Text += string.Join("", screenList.ToArray()) + "\n\n";
            //}
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {

        }
    }
}